package com.xfly.app.ui;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.ptmall.app.R;
import com.ptmall.app.base.BaseMvpActivity;
import com.ptmall.app.base.PermissionListener;
import com.ptmall.app.bean.model.db.Account;
import com.ptmall.app.net.HttpMethods;
import com.ptmall.app.net.api.ApiDataRepository;
import com.ptmall.app.net.base.ApiNetResponse;
import com.ptmall.app.net.okhttp.BusinessResponse;
import com.ptmall.app.net.okhttp.OkHttps;
import com.ptmall.app.utils.AllUtils;
import com.ptmall.app.utils.FileUtils;
import com.ptmall.app.utils.GlideUtil;
import com.ptmall.app.utils.UriUtil;
import com.ptmall.app.view.CircularImage;
import com.ptmall.app.view.TitleBarView;
import com.xfly.app.bean.UpBean;
import com.xfly.app.bean.UserBean;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserSetActivity extends BaseMvpActivity implements View.OnClickListener, BusinessResponse {

    EditText name;
    CircularImage topimg;
    Button btn;


    PopupWindow popupWindow;
    private View popView;

    private Uri cropImageUri;
    private Uri takePicUri;
    private final int CROP_IMG_WIDTH = 700;
    private final int CROP_IMG_HEIGHT = 700;

    private final int TAKE_PICTURE = 0x000001;
    private final int CHOOSE_PICTURE = 0x000002;
    private final int CROP_SMALL_PICTURE = 0x000003;


    private String[] VIDEO_PERMISSION = {
            Manifest.permission.CAMERA,
            //Manifest.permission.RECORD_AUDIO,
            //Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    ApiDataRepository apiDataRepository = ApiDataRepository.getInstance();

    String fileid = "";


    private OkHttps okHttps;

    UpBean mUpBean;
    UserBean mUserBean;

    TitleBarView title_bar;
    TextView setimg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_userset);
    }

    @Override
    public void initViews() {
        name = findViewById(R.id.name);
        topimg = findViewById(R.id.topimg);
        btn = findViewById(R.id.btn);
        title_bar = findViewById(R.id.title_bar);
        setimg = findViewById(R.id.setimg);
    }

    @Override
    public void initEvents() {
        getData();

        okHttps = new OkHttps(this);
        okHttps.addResponseListener(this);
        title_bar.setText("个人设置");
        title_bar.setOnTitleBarClickListener(new TitleBarView.TitleBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setData();
            }
        });

        topimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestRuntimePermisssions(VIDEO_PERMISSION, new PermissionListener() {
                    @Override
                    public void onGranted() {//同意
                        pop();
                    }

                    @Override
                    public void onDenied(List<String> deniedList) {
                    }
                });

            }
        });
        setimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestRuntimePermisssions(VIDEO_PERMISSION, new PermissionListener() {
                    @Override
                    public void onGranted() {//同意
                        pop();
                    }

                    @Override
                    public void onDenied(List<String> deniedList) {
                    }
                });

            }
        });
    }

    private void getData(){
        apiDataRepository.myInfo(null, new ApiNetResponse<UserBean>() {
            @Override
            public void onSuccess(UserBean data) {
                mUserBean = data;
                GlideUtil.showImg(getContext(),data.getAvatar(),topimg);
                name.setText(data.getName());

            }
        });
    }

    private void setData(){
        Map<String,String> map = new HashMap<>();
        if(mUpBean!=null){
            map.put("avatar",mUpBean.getId());
        }else {
            map.put("avatar",mUserBean.getAvatar_id()+"");
        }
        map.put("name",name.getText().toString());
        apiDataRepository.setinfo(map, new ApiNetResponse<Object>() {
            @Override
            public void onSuccess(Object data) {
                showMsg("修改成功");
                finish();
            }
        });
    }


    private void pop() {
        if (null == popupWindow) {
            if (null == popView) {
                popView = LayoutInflater.from(this).inflate(R.layout.personaldata_pop, null);
                popView.findViewById(R.id.btn1).setOnClickListener(this);
                popView.findViewById(R.id.btn2).setOnClickListener(this);
                popView.findViewById(R.id.btn_cancel).setOnClickListener(this);
            }
//            View view = LayoutInflater.from(this).inflate(R.layout.personaldata_pop, null);
            popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            popupWindow.setAnimationStyle(R.style.dialogAnim);
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
            AllUtils.backgroundAlpha(0.5f, getWindow());
            popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    AllUtils.backgroundAlpha(1.0f, getWindow());
                }
            });
            //popupWindow.showAtLocation(rootView, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
        } else {
            AllUtils.backgroundAlpha(0.5f, getWindow());
            popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TAKE_PICTURE:
//                        String fileName = String.valueOf(System.currentTimeMillis());
//                        Bitmap bm = (Bitmap) data.getExtras().get("data");
//                        String path = FileUtils.saveBitmap(bm);
//                        if (null != path) {
//                            File f = new File(path);
//                            if (f.exists()) {//存在的话 保存成功
//                                //启动图片剪切
//                                cutImage(UriUtil.getFileUri(PersonalData.this,f)/* Uri.fromFile(f)*/);
//                            }
//                        }
                    if (null != takePicUri) {
                        cropImageUri(takePicUri, CROP_IMG_WIDTH, CROP_IMG_HEIGHT, CROP_SMALL_PICTURE);
                    }
                    break;
                case CHOOSE_PICTURE:
                    //cutImage(data.getData());
                    cropImageUri(data.getData(), CROP_IMG_WIDTH, CROP_IMG_HEIGHT, CROP_SMALL_PICTURE);
                    break;
                case CROP_SMALL_PICTURE:
                    setImageToView(data);
                    break;

                default:
                    break;
            }
        }
    }


    /**
     * 设置头像
     */
    protected void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        Bitmap bitmap = null;
        if (extras != null) {
            bitmap = extras.getParcelable("data");
        }
        if (null == bitmap) {
            try {
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), cropImageUri);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null == bitmap) {
            return;
        }

        topimg.setImageBitmap(bitmap);

        FileUtils.saveBitmap(bitmap, "123456");

        okHttps.postAsynFile(HttpMethods.BASE_URL + "attachment/upload", new File(FileUtils.SDPATH + "123456.JPEG"), true, 1);

    }



    /**
     * 裁剪图片
     *
     * @param uri
     * @param outputX
     * @param outputY
     * @param requestCode
     */
    private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) {
        String fileName = FileUtils.SDPATH + String.valueOf(System.currentTimeMillis()) + ".jpg";
        String local = FileUtils.SDPATH;
        File folder = new File(local);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        cropImageUri = Uri.fromFile(new File(fileName));
//        cropImageUri = getSomeUri();

        // cropImageUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        //是否裁剪
        intent.putExtra("crop", "true");
        //设置xy的裁剪比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        //设置输出的宽高
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        //是否缩放
        intent.putExtra("scale", false);
        //输入图片的Uri，指定以后，可以在这个uri获得图片
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropImageUri);
        //是否返回图片数据，可以不用，直接用uri就可以了
        intent.putExtra("return-data", false);
        //设置输入图片格式
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        //是否关闭面部识别
        intent.putExtra("noFaceDetection", true); // no face detection
        //启动
        startActivityForResult(intent, requestCode);
    }

    /**
     * 创建任一Uri
     *
     * @return
     */
    private Uri getSomeUri() {
        String fileName = FileUtils.SDPATH + String.valueOf(System.currentTimeMillis()) + ".jpg";
        String local = FileUtils.SDPATH;
        File folder = new File(local);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        return UriUtil.getFileUri(getContext(), new File(fileName));
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn1://拍照
                takePicUri = getSomeUri();
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                openCameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, takePicUri);
                startActivityForResult(openCameraIntent, TAKE_PICTURE);
                popupWindow.dismiss();
                break;
            case R.id.btn2://本地相册
                Intent openAlbumIntent = new Intent(
                        Intent.ACTION_PICK);
                openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                //用startActivityForResult方法，待会儿重写onActivityResult()方法，拿到图片做裁剪操作
                startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
//                intent = new Intent(PersonalData.this,
//                        AlbumActivity.class);
//                startActivity(intent);
                popupWindow.dismiss();
                break;
            case R.id.btn_cancel:
                popupWindow.dismiss();
                break;

        }
    }

    @Override
    public void OnMessageResponse(int id, String jo) {
        switch (id) {
            case 1:
                mUpBean = okHttps.getGson().fromJson(jo, new TypeToken<UpBean>() {
                }.getType());
                break;
        }
    }
}
